package com.zzx.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.zzx.common.core.controller.BaseController;
import com.zzx.common.core.domain.entity.SysDept;
import com.zzx.common.core.domain.entity.SysRole;
import com.zzx.common.core.domain.entity.SysUser;
import com.zzx.common.core.page.TableDataInfo;
import com.zzx.entity.ApiResult;
import com.zzx.system.service.ISysDeptService;
import com.zzx.system.service.ISysPostService;
import com.zzx.system.service.ISysRoleService;
import com.zzx.system.service.ISysUserService;
import com.zzx.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/user")
@Api(tags = "系统用户管理")
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    /**
     * 获取用户列表
     */
    @ApiOperation("获取用户列表")
//    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

//    @ApiOperation("导出用户数据")
//    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
//    @PreAuthorize("@ss.hasPermi('system:user:export')")
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, SysUser user)
//    {
//        List<SysUser> list = userService.selectUserList(user);
//        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
//        util.exportExcel(response, list, "用户数据");
//    }
//
//    @ApiOperation("导入用户数据")
//    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
//    @PreAuthorize("@ss.hasPermi('system:user:import')")
//    @PostMapping("/importData")
//    public ApiResult importData(MultipartFile file, boolean updateSupport) throws Exception
//    {
//        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
//        List<SysUser> userList = util.importExcel(file.getInputStream());
//        String operName = getUsername();
//        String message = userService.importUser(userList, updateSupport, operName);
//        return success(message);
//    }
//
//    @ApiOperation("下载用户导入模板")
//    @PostMapping("/importTemplate")
//    public void importTemplate(HttpServletResponse response)
//    {
//        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
//        util.importTemplateExcel(response, "用户数据");
//    }

    /**
     * 根据用户编号获取详细信息
     */
    @ApiOperation("查询用户详情")
//    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public ApiResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        JSONObject jsonObject = new JSONObject();
        if (StringUtils.isNotNull(userId)) {
            userService.checkUserDataScope(userId);
            SysUser sysUser = userService.selectUserById(userId);
            jsonObject.put("user", sysUser);
            jsonObject.put("postIds", postService.selectPostListByUserId(userId));
            jsonObject.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        List<SysRole> roles = roleService.selectRoleAll();
        jsonObject.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        jsonObject.put("posts", postService.selectPostAll());
        return ApiResult.ok(jsonObject);
    }

    /**
     * 新增用户
     */
    @ApiOperation("新增用户")
//    @PreAuthorize("@ss.hasPermi('system:user:add')")
//    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public ApiResult add(@Validated @RequestBody SysUser user) {
        deptService.checkDeptDataScope(user.getDeptId());
        roleService.checkRoleDataScope(user.getRoleIds());
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
//        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @ApiOperation("修改用户")
//    @PreAuthorize("@ss.hasPermi('system:user:edit')")
//    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public ApiResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
//        userService.checkUserDataScope(user.getUserId());
//        deptService.checkDeptDataScope(user.getDeptId());
//        roleService.checkRoleDataScope(user.getRoleIds());
//        if (!userService.checkUserNameUnique(user)) {
//            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
//        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
//            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
//        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
//            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
//        }
//        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @ApiOperation("删除用户")
//    @PreAuthorize("@ss.hasPermi('system:user:remove')")
//    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public ApiResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
//    @ApiOperation("重置用户密码")
////    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
////    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
//    @PutMapping("/resetPwd")
//    public ApiResult resetPwd(@RequestBody SysUser user)
//    {
//        userService.checkUserAllowed(user);
//        userService.checkUserDataScope(user.getUserId());
//        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
//        user.setUpdateBy(getUsername());
//        return toAjax(userService.resetPwd(user));
//    }

    /**
     * 状态修改
     */
    @ApiOperation("修改用户状态")
//    @PreAuthorize("@ss.hasPermi('system:user:edit')")
//    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public ApiResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @ApiOperation("获取用户授权的角色")
//    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public ApiResult authRole(@PathVariable("userId") Long userId) {
        JSONObject jsonObject = new JSONObject();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        jsonObject.put("user", user);
        jsonObject.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ApiResult.ok(jsonObject);
    }

    /**
     * 用户授权角色
     */
    @ApiOperation("授予用户角色权限")
//    @PreAuthorize("@ss.hasPermi('system:user:edit')")
//    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public ApiResult insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        roleService.checkRoleDataScope(roleIds);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @ApiOperation("获取用户管理对应的部门树")
//    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTree")
    public ApiResult deptTree(SysDept dept) {
        return success(deptService.selectDeptTreeList(dept));
    }






//    @ApiOperation(value = "新增、编辑")
//    @RequestMapping(value="/add",method = RequestMethod.POST)
//    public ApiResult add(@RequestBody SysUser param) {
//        userService.add(param);
//        return ApiResult.ok();
//    }


    @ApiOperation(value = "删除")
    @RequestMapping(value="/deleteById",method = RequestMethod.POST)
    public ApiResult deleteById(@RequestBody SysUser param) {
        userService.deleteById(param);
        return ApiResult.ok();
    }

    @ApiOperation(value = "列表查询")
    @RequestMapping(value="/selectBy",method = RequestMethod.POST)
    public ApiResult selectBy(@RequestBody SysUser param) {

        return ApiResult.ok(userService.selectBy(param));
    }

    @ApiOperation(value = "编辑员工信息和新增公司")
    @RequestMapping(value="/editTUserAndTCompany",method = RequestMethod.POST)
    public ApiResult editTUserAndTCompany(@RequestBody SysUser param) {
        JSONObject res = userService.editTUserAndTCompany(param);
        return ApiResult.ok(res);
    }

    @ApiOperation(value = "根据ID查询")
    @RequestMapping(value="/findById/{userId}",method = RequestMethod.GET)
    public ApiResult findById(@PathVariable Long userId ) {
        SysUser res = userService.findById(userId);
        return ApiResult.ok(res);
    }
}
